/**
 * Malsha 2014/09/23
 */
PledgeDtails = new Object();

var pledge_customer_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'code', 'title', 'initials', 'surname', 'denotedByInitials', 'nicPassport', 'customerType', 'accountType', 'residential', 'fmId', 'correspondingAddress',
			'generalAddress', 'phone', 'fax', 'corresEmail', 'corresFax', 'corresPost', 'corresInst', 'bankInstrution', 'organizationName', 'businessRegNo', 'businessAddress' ]
});
var pledge_investment_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'customer', 'investment', 'invesCode', 'totalUnits', 'totalAmount', 'type', 'pledgeUnits', 'pledgeAmount', 'fundid', 'description', 'fundUnitVal' ]
});
var pledge_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'customer', 'investment', 'invesCode', 'pledgeUnits', 'pledgeAmount', 'fundid', 'description', 'fundUnitVal' ]
});
var pledge_fund_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'name', 'code', 'unitValue' ]
});

PledgeDtails.getPledgeGird = function() {

	pledge_investment_store.removeAll();
	var grid = null;
	grid = Ext.create('Ext.grid.Panel', {
		title : 'Pledege Details',
		store : pledge_store,
		height : 200,
		padding : '10 0 0 0',
		id : 'avi_pledge_grid',
		columns : [ {
			header : 'Investment Code',
			dataIndex : 'invesCode',
			width : 150
		}, {
			header : 'Pledge Units',
			dataIndex : 'pledgeUnits',
			width : 150,
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
		}, {
			header : 'Description',
			dataIndex : 'description',
			flex : 1
		}, {
			xtype : 'actioncolumn',
			width : 100,
			align : 'center',
			items : [ {
				icon : 'images/release.png',
				tooltip : 'Click for Release this Units',
				handler : function(grid, rowIndex, colIndex) {
					var myMask = new Ext.LoadMask(formpanel, {
						msg : "Please wait..."
					});
					myMask.show();
					var rec = grid.getStore().getAt(rowIndex);
					var form = this.up('form').getForm();
					Ext.Ajax.request({
						url : 'releaseunits.action',
						params : {
							"pledgeid" : rec.get('id')
						},
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							pledge_store.remove(rec);
							form.reset();
							myMask.hide();
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', action.result.resulteMsg);
						}
					});
				}
			} ]
		} ]
	});

	return grid;
};

PledgeDtails.getGird = function() {

	pledge_investment_store.removeAll();
	var grid = null;
	grid = Ext.create('Ext.grid.Panel', {
		title : 'Investment',
		store : pledge_investment_store,
		height : 200,
		id : 'pledge_grid',
		plugins : [ Ext.create('Ext.grid.plugin.CellEditing', {
			clicksToEdit : 1
		}) ],
		columns : [ {
			header : 'Investment Code',
			dataIndex : 'invesCode',
			width : 100
		}, {
			header : 'No Of Units',
			dataIndex : 'totalUnits',
			width : 125,
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
		}, {
			header : 'Amount',
			dataIndex : 'totalAmount',
			width : 125,
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
		}, {
			header : 'Type',
			dataIndex : 'type',
			width : 85,
			align : 'center',
			editor : {
				xtype : 'combo',
				displayField : 'name',
				valueField : 'name',
				value : 'U',
				store : Ext.create('Ext.data.Store', {
					fields : [ 'name', 'type' ],
					data : [ {
						name : 'Unit',
						type : 'U'
					}, {
						name : 'Value',
						type : 'V'
					} ]
				})
			}
		}, {
			header : 'Pledge Amount',
			dataIndex : 'pledgeAmount',
			id : 'releaseAmount',
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
			flex : 1,
			getEditor : function(record) {
				var stype = grid.getView().getSelectionModel().getSelection()[0].get('type');
				if (stype == 'Value') {
					var max = grid.getView().getSelectionModel().getSelection()[0].get('fundUnitVal') * grid.getView().getSelectionModel().getSelection()[0].get('totalUnits');
					return Ext.create('Ext.grid.CellEditor', {
						field : {
							xtype : 'numberfield',
							hideTrigger : true,
							keyNavEnabled : false,
							msgTarget : 'side',
							mouseWheelEnabled : false,
							decimalPrecision : 4,
							maxValue : max
						}
					});
				} else
					return false;
			}
		}, {
			header : 'Pledge Units',
			dataIndex : 'pledgeUnits',
			id : 'releaseUnits',
			xtype : 'numbercolumn',
			format : '0,000.0000',
			align : 'right',
			flex : 1,
			getEditor : function(record) {
				var stype = grid.getView().getSelectionModel().getSelection()[0].get('type');
				if (stype == 'Unit') {
					return Ext.create('Ext.grid.CellEditor', {
						field : {
							xtype : 'numberfield',
							hideTrigger : true,
							keyNavEnabled : false,
							mouseWheelEnabled : false,
							msgTarget : 'side',
							decimalPrecision : 4,
							maxValue : grid.getView().getSelectionModel().getSelection()[0].get('totalUnits')
						}
					});
				} else
					return false;
			}
		}, {
			header : 'Description',
			dataIndex : 'description',
			flex : 1,
			getEditor : function(record) {
				return Ext.create('Ext.grid.CellEditor', {
					field : {
						xtype : 'textfield',
						msgTarget : 'side'
					}
				});
			}
		} ]
	});
	grid.on('edit', function(editor, e) {

		var unitPrice = e.record.data.fundUnitVal;
		if (unitPrice != null || unitPrice != "") {
			if (e.field == 'pledgeAmount') {
				var enterdValue = e.record.data.pledgeAmount;
				e.record.data.pledgeUnits = enterdValue / unitPrice;
				e.record.commit();
			}

			if (e.field == 'pledgeUnits') {
				var enterdValue = e.record.data.pledgeUnits;
				e.record.data.pledgeAmount = enterdValue * unitPrice;
				e.record.commit();
			}
		}

	});
	return grid;
};

PledgeDtails.getCenterPanel = function() {

	var investmentGrid = PledgeDtails.getGird();
	var pledgeGrid = PledgeDtails.getPledgeGird();
	return formpanel = Ext.create('Ext.form.Panel', {
		title : '<B>Pledge Details</B>',
		bodyPadding : '20',
		autoScroll : true,
		defaults : {
			anchor : '85%'
		},
		frame : true,
		items : [ {
			xtype : 'combo',
			fieldLabel : 'Customer<span style="color:red">*</span>',
			flex : 1,
			labelWidth : 90,
			anchor : '40%',
			padding : '0 10 0 0',
			store : pledge_customer_store,
			valueField : 'id',
			displayField : 'code',
			emptyText : 'Select a Customer...',
			isLoaded : false,
			allowBlank : false,
			msgTarget : 'under',
			name : 'customer',
			id : 'customer_id',
			queryMode : 'local',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - {surname}</div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {surname}', '</tpl>'),
			listeners : {
				expand : function(combo, opt) {
					if (!combo.isLoaded) {
						Ext.Ajax.request({
							url : 'getCustomer.action',
							success : function(response) {
								var obj = Ext.decode(response.responseText);
								combo.getStore().loadRawData(obj.customerBeans);
								combo.isLoaded = true;
							}
						});
					}
				}
			}
		}, {
			xtype : 'combo',
			fieldLabel : 'Fund<span style="color:red">*</span>',
			flex : 1,
			labelWidth : 90,
			anchor : '40%',
			id : 'fund',
			padding : '0 10 0 0',
			store : pledge_fund_store,
			valueField : 'id',
			displayField : 'code',
			emptyText : 'Select a Fund...',
			isLoaded : false,
			allowBlank : false,
			msgTarget : 'under',
			name : 'fundid',
			queryMode : 'local',
			tpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '<div class="x-boundlist-item">{code} - {name}</div>', '</tpl>'),
			displayTpl : Ext.create('Ext.XTemplate', '<tpl for=".">', '{code} - {name}', '</tpl>'),
			listeners : {
				expand : function(combo, opt) {
					if (!combo.isLoaded) {
						Ext.Ajax.request({
							url : 'getFundVsUnitValue.action',
							success : function(response) {
								var obj = Ext.decode(response.responseText);
								combo.getStore().loadRawData(obj.fundDtos);
								combo.isLoaded = true;
							}
						});
					}
				}
			},
			listConfig : {
				listeners : {
					itemclick : function(list, record) {
						var customer = Ext.getCmp('customer_id').getValue();
						if (customer != null) {
							Ext.Ajax.request({
								url : 'getInvestmentByFundId.action',
								params : {
									"fundId" : record.get('id'),
									"customerId" : customer
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									pledge_investment_store.removeAll();
									pledge_investment_store.loadRawData(obj.pledgeDtos);
								}
							});
							Ext.Ajax.request({
								url : 'getPledges.action',
								params : {
									"fundId" : record.get('id'),
									"customerId" : customer
								},
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									pledge_store.removeAll();
									pledge_store.loadRawData(obj.pledgeDtos);
								}
							});
						} else {
							this.up('form').getForm().reset();
							Ext.Msg.alert('Failed', "Plase select Customer");
						}

					}
				}
			}
		}, investmentGrid, pledgeGrid ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				Ext.getCmp('pledge_grid').getStore().removeAll();
				this.up('form').getForm().reset();
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = this.up('form').getForm();
				var grids = Ext.getCmp('pledge_grid');
				if (form.isValid()) {
					var pledges = [];
					grids.getStore().each(function(record) {
						if (record.get('pledgeUnits') > 0) {
							var obj = {
								"customer" : record.get("customer"),
								"investment" : record.get("investment"),
								"totalUnits" : record.get("totalUnits"),
								"type" : record.get("type"),
								"pledgeUnits" : record.get("pledgeUnits"),
								"pledgeAmount" : record.get("pledgeAmount"),
								"description" : record.get("description"),
								"fundUnitVal" : record.get("fundUnitVal"),
								"fundid" : record.get("fundid")
							};
							pledges.push(obj);
						}
					});
					console.log(pledges);
					form.url = 'addPledgeDetails.action';
					form.submit({
						params : {
							"pledges" : Ext.encode(pledges)
						},
						success : function(form, action) {
							form.reset();
							Ext.getCmp('save').setText('Save');
							Ext.Msg.alert('Success', 'Saved Successfully');
							Ext.getCmp('pledge_grid').getStore().removeAll();
						},
						failure : function(form, action) {
							Ext.Msg.alert('Failed', action.result.resulteMsg);
						}
					});
				}
			}
		} ]
	});
};